package cn.wf.order.message;

import cn.wf.order.utils.JsonUtil;
import cn.wf.product.ProductInfoOutput;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description  接收商品服务扣库存发来的消息
 * @Author 万飞
 * @Date 2018/8/12 4:34
 */
@Component
@Slf4j
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";  //后面跟的是productId

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message) {
        //message => ProductInfoOutput
        //将数组字符串json转换为list集合
        List<ProductInfoOutput> productInfoOutputList = (List<ProductInfoOutput>) JsonUtil.fromJson(message, new TypeReference<List<ProductInfoOutput>>(){});
        log.info("【接收消息】订单服务从商品服务队列【{}】接收到消息: {}", "productInfo", productInfoOutputList);

        //存储到redis中
        for (ProductInfoOutput p: productInfoOutputList) {
            //key是id,value是库存
            redisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, p.getProductId()), String.valueOf(p.getProductStock()));
        }
    }
}
